const { UserNotFoundError } = require('../../domain/user/error')
const Usecase = require('../../shared/usecase/Usecase')

class ResetPassword extends Usecase {
  constructor({ userRepo, config, database, currentUser }) {
    super()
    this.userRepo = userRepo
    this.defaultPassword = config.get('defaultPassword')
    this.sequelize = database.sequelize
    this.currentUser = currentUser
  }

  async execute(userId) {
    const user = await this.userRepo.findById(userId)
    if (!user) throw new UserNotFoundError(userId)
    user.password = this.defaultPassword
    await user.bcryptPassword()
    const transaction = await this.sequelize.transaction()
    try {
      await this.userRepo.update(user, {
        transaction,
        currentUser: this.currentUser,
      })
      await transaction.commit()
    } catch (error) {
      await transaction.rollback()
      throw error
    }
  }
}

module.exports = ResetPassword
